package com.hethongviet.job;

import org.json.JSONException;
import org.json.JSONObject;

import com.hethongviet.job.helpers.JSONAttributes;
import com.hethongviet.job.helpers.JSONHelper;
import com.hethongviet.job.helpers.ServiceHelper;
import com.hethongviet.job.models.Project;
import com.hethongviet.job.pages.MainActivity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;

public class JobTrackingActivity extends Activity
{
	private EditText _editTextUsername = null;
	private EditText _editTextPassword = null;
	private EditText _editTextActivationCode = null;

	private CheckBox _checkBoxAutoLogin = null;
	private CheckBox _checkBoxRemember = null;

	private Button _buttonLogin = null;
	private Button _buttonCancel = null;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		/* Full screen */
		AppMain.makeFullScreen(this);

		setContentView(R.layout.main);

		_buttonLogin = (Button) findViewById(R.id.buttonLogin);
		_buttonCancel = (Button) findViewById(R.id.buttonCancel);
		_editTextActivationCode = (EditText) findViewById(R.id.editTextAcitvationCode);
		_editTextPassword = (EditText) findViewById(R.id.editTextPassword);
		_editTextUsername = (EditText) findViewById(R.id.editTextUsername);
		_checkBoxAutoLogin = (CheckBox) findViewById(R.id.checkboxAutoLogin);
		_checkBoxRemember = (CheckBox) findViewById(R.id.checkboxRemember);

		if (AppMain._isDebug)
		{
			_editTextActivationCode.setText("UPJ5CBFT");
			_editTextPassword.setText("123456789");
			_editTextUsername.setText("dinhngoctan.cntt@gmail.com");
		}

		_buttonCancel.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0)
			{
				/* Reset all fields */
				_editTextActivationCode.setText("");
				_editTextPassword.setText("");
				_editTextUsername.setText("");
				_checkBoxAutoLogin.setChecked(false);
				_checkBoxRemember.setChecked(false);
			}
		});

		_buttonLogin.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0)
			{
				String username = _editTextUsername.getText().toString();
				if (username == null || username.equalsIgnoreCase(""))
				{
					AppMain.alert(JobTrackingActivity.this,
							getString(R.string.textError),
							getString(R.string.textErrorEmptyInput) + " "
									+ getString(R.string.textUsername));
					return;
				}

				String password = _editTextPassword.getText().toString();
				if (password == null || password.equalsIgnoreCase(""))
				{
					AppMain.alert(JobTrackingActivity.this,
							getString(R.string.textError),
							getString(R.string.textErrorEmptyInput) + " "
									+ getString(R.string.textPassword));
					return;
				}

				String activationCode = _editTextActivationCode.getText().toString();
				if (activationCode == null
						|| activationCode.equalsIgnoreCase(""))
				{
					AppMain.alert(JobTrackingActivity.this,
							getString(R.string.textError),
							getString(R.string.textErrorEmptyInput) + " "
									+ getString(R.string.textAcitvationCode));
					return;
				}

				if (activationCode.length() != AppMain.ACTIVATION_CODE_CHAR_LENGTH)
				{
					AppMain.alert(
							JobTrackingActivity.this,
							getString(R.string.textError),
							getString(R.string.textErrorEmptyInput)
									+ " "
									+ getString(R.string.textErrorMessageWrongActivationCode));
					return;
				}

				if (_checkBoxAutoLogin.isChecked())
				{
					Log.d("Debug", "check.........................");
				}
				else
				{
					Log.d("Debug", "no check.........................");
					doLogin(_editTextUsername.getText().toString(),
							_editTextPassword.getText().toString(),
							_editTextActivationCode.getText().toString());
				}
			}
		});
	}

	private void gotoPageMain()
	{
		Intent intent = new Intent(JobTrackingActivity.this, MainActivity.class);
		startActivity(intent);
	}

	private void doLogin(String username, String password, String activationCode)
	{
		String resultString = ServiceHelper.doLogin(username, password,
				activationCode);

		/* Return the error code 0, 1, 2, 3 */
		if (resultString.length() < 3)
		{
			int error = -1;
			try
			{
				error = Integer.parseInt(resultString);
			} catch (NumberFormatException numberFormatException)
			{
				numberFormatException.printStackTrace();
			}
			String errorString = "";
			switch (error)
			{
				case AppMain.ERROR_CODE_ACTIVATION_CODE_OUT_OF_DATE:
					errorString = getString(R.string.textErrorMessageActivationCodeOutOfDate);
					break;
				case AppMain.ERROR_CODE_ACTIVATION_CODE_USED_BY_OTHER:
					errorString = getString(R.string.textErrorMessageAcivationCodeUsedByOther);
					break;
				case AppMain.ERROR_CODE_WRONG_ACTIVATION_CODE:
					errorString = getString(R.string.textErrorMessageWrongActivationCode);
					break;
				case AppMain.ERROR_CODE_WRONG_USERNAME_OR_PASSWORD:
					errorString = getString(R.string.textErrorMessageWrongUsernameOrPassword);
					break;
				default:
					errorString = getString(R.string.textErrorNetwork);
					break;
			}
			AppMain.alert(JobTrackingActivity.this,
					getString(R.string.textError), errorString);
			return;
		}

		/* Temporary */
		if (resultString.charAt(0) != '{')
		{
			AppMain.alert(JobTrackingActivity.this,
					getString(R.string.textError), resultString);
			return;
		}

		/* Return JSON : Successful */
		AppMain._user.setUsername(username);
		AppMain._user.setPassword(password);
		AppMain._user.setActivationCode(activationCode);
		AppMain._user.setAutoLogin(_checkBoxAutoLogin.isChecked());
		AppMain._user.setRemember(_checkBoxRemember.isChecked());

		// resultString =
		// "{\"FK_UserID\":\"d709460b-0f94-4e6b-aca7-4ceb7f2dc712\",\"UserName\":\"dinhngoctan.cntt@gmail.com\",\"PasswordLogin\":\"wI6wL7kuliDrQ+19K7FqmMdHqex522o+MFENwglKDUA=\",\"FK_MemberID\":\"53ec32b9-57e8-4306-a418-d87a44e7c0fc\",\"IsManagerJob\":\"False\",\"CompanyName\":\"VSYS JOIN STOCK COMPANY\"}";
		resultString.subSequence(0, resultString.length() - 2);
		JSONObject jsonObject = null;
		try
		{
			jsonObject = new JSONObject(resultString);
		} catch (JSONException e)
		{
			e.printStackTrace();
			AppMain.alert(JobTrackingActivity.this,
					getString(R.string.textError),
					getString(R.string.textErrorNetwork));
			return;
		}
		AppMain._user.setId(JSONHelper.getString(jsonObject,
				JSONAttributes.USER_ID));
		AppMain._user.setMemberId(JSONHelper.getString(jsonObject,
				JSONAttributes.USER_MEMBER_ID));
		AppMain._user.setManagerJobs(Boolean.parseBoolean(JSONHelper.getString(
				jsonObject, JSONAttributes.USER_IS_MANAGER_JOB)));
		AppMain._user.setComputerName(JSONHelper.getString(jsonObject,
				JSONAttributes.USER_COMPANY_NAME));

		/* Get list of projects */
		String resultProjectsString = ServiceHelper.doGetListOfProjects(
				username, AppMain._user.getMemberId(),
				AppMain._user.isManagerJobs());
		// Temporary
		if (resultProjectsString == null
				|| resultProjectsString.equalsIgnoreCase("")
				|| resultProjectsString.charAt(0) != '{')
		{
			AppMain.alert(JobTrackingActivity.this,
					getString(R.string.textError), getString(R.string.textErrorNetwork));
			return;
		}
		//
		String[] jsonStrings = resultProjectsString.split("&");
		AppMain._projectsList.clear();
		for (int i = 0; i < jsonStrings.length; i++)
		{
			Log.d("Debug", "Project index " + i);
			try
			{
				jsonObject = new JSONObject(jsonStrings[i]);
			} catch (JSONException e)
			{
				e.printStackTrace();
				AppMain.alert(JobTrackingActivity.this,
						getString(R.string.textError),
						getString(R.string.textErrorNetwork));
				return;
			}

			Project project = new Project();
			project.setCode(JSONHelper.getString(jsonObject,
					JSONAttributes.PROJECT_CODE));
			project.setDateCreated(JSONHelper.getString(jsonObject,
					JSONAttributes.PROJECT_DATE_CREATE));
			project.setDateFinish(JSONHelper.getString(jsonObject,
					JSONAttributes.PROJECT_DATE_FINISH));
			project.setDateStart(JSONHelper.getString(jsonObject,
					JSONAttributes.PROJECT_DATE_START));
			project.setDescription(JSONHelper.getString(jsonObject,
					JSONAttributes.PROJECT_DECRIPTION));
			project.setGroupName(JSONHelper.getString(jsonObject,
					JSONAttributes.PROJECT_GROUP_NAME));
			project.setId(JSONHelper.getString(jsonObject,
					JSONAttributes.PROJECT_ID));
			project.setManagerName(JSONHelper.getString(jsonObject,
					JSONAttributes.PROJECT_MANAGER_NAME));
			project.setMemberCreatingName(JSONHelper.getString(jsonObject,
					JSONAttributes.PROJECT_MEMBER_CREATE_NAME));
			project.setWorker(JSONHelper.getString(jsonObject,
					JSONAttributes.PROJECT_MEMBER_CREATE_NAME));
			project.setName(JSONHelper.getString(jsonObject,
					JSONAttributes.PROJECT_NAME));
			project.setNote(JSONHelper.getString(jsonObject,
					JSONAttributes.PROJECT_NOTE));

			AppMain._projectsList.add(project);

		}
		/** Go to the main page */
		gotoPageMain();
	}

}
